/*
 * @Author: yangrongxin
 * @Date: 2021-12-21 16:05:00
 * @LastEditors: guoju
 * @LastEditTime: 2022-01-07 16:34:02
 */

import { useEffect, useState } from 'react';
import { View, Text, Label, Checkbox } from '@tarojs/components';
import { optionLabel } from '@/restful/utils';
import type { MuiltChoise } from '@/types/exam.d';
import type { ComProps } from '../index.d';
import styles from './index.module.less';

interface IMuiltSelect extends ComProps {
  extend: MuiltChoise
}

const MuiltSelect = (props: IMuiltSelect) => {
  const {
    extend = [],
    answer = [],
    label = [],
    setAnswer
  } = props;

  const [options, setOptions] = useState([]);
  const [checkedList, setCheckedList] = useState<any>([]);
  const [checkedLabel, setCheckedLabel] = useState<any>([]);

  useEffect(() => {
    let list = JSON.parse(JSON.stringify(extend));
    list?.map((item: any, index: number) => {
      item.content = `${optionLabel[index]}. ${item.content}`;
    });
    setOptions(list);
  }, [extend]);

  useEffect(() => {
    setCheckedList(answer);
    setCheckedLabel(label);
  }, [answer]);

  const onChange = (item, index) => {
    let list = JSON.parse(JSON.stringify(checkedList));
    let labels = JSON.parse(JSON.stringify(checkedLabel));

    const val = item.answerId;
    const i = list.indexOf(val);

    if (i > -1) {
      list.splice(i, 1);
      labels.splice(i, 1);
    } else {
      list.push(val);
      labels.push(optionLabel[index]);
    }
    setCheckedList(list);
    setCheckedLabel(labels);
    setAnswer({
      answer: list,
      label: labels,
    }, '');
  };

  return <View className={styles.muiltSelectContainer}>
    <View className={styles.muiltSelect} >
      {options?.map((item, index) => {
        const { content, answerId } = item;
        const isSelect = checkedList.includes(answerId);
        return (
          <Label key={answerId} className={`${styles.selectItem} ${isSelect ? styles.actived : ''}`} onClick={() => onChange(item, index)}>
            <Checkbox value={answerId} className={styles.checkbox} checked={isSelect}/>
            <Text className={styles.text}>{content}</Text>
          </Label>
        )}
      )}
    </View>
  </View>;
};

export default MuiltSelect;
